package com.gitee.magic.context.converter;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonObject;

/**
 * @author start
 */
public class MapConverterEditor extends AbstractConverterEditor<String> {
	
	private AbstractConverterEditor<?> kEditor;
	private AbstractConverterEditor<?> vEditor;
	
	public MapConverterEditor(Class<?> prototype) {
		super(prototype);
	}
	
	public void setGeneric(Type genericType,Type typeReference) {
		kEditor=ConverterEditorUtils.getGenericEditor(genericType, typeReference, 0);
		vEditor=ConverterEditorUtils.getGenericEditor(genericType, typeReference, 1);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			Class<?> target=value.getClass();
			JsonObject json;
			if(target.equals(JsonObject.class)) {
				json=(JsonObject)value;
			}else {
				json=new JsonObject(String.valueOf(value));
			}
			Map<Object,Object> map=new HashMap<>(100);
			Iterator<String> keys=json.keys();
			while(keys.hasNext()) {
				String key=keys.next();
				kEditor.restore(key);
				vEditor.restore(json.get(key));
				map.put(kEditor.getValue(), vEditor.getValue());
			}
			setValue(map);
		}
	}
	
	@Override
	public String converter() {
		if (getSource() == null) {
			return null;
		}
		return getSource().toString();
	}

	@Override
	public void setValue(Object v) {
		super.setValue(v);
		if(getValue()!=null) {
			Map<?,?> val=(Map<?,?>)getValue();
			JsonObject json=new JsonObject();
			for(Object k:val.keySet()) {
				Class<?> kCls=k.getClass();
				AbstractConverterEditor<?> keyEditor=ConverterEditorUtils.getBasicConverter(kCls);
				keyEditor.setValue(k);
				Object vval=val.get(k);
				if(vval!=null) {
					Class<?> vCls=vval.getClass();
					AbstractConverterEditor<?> valEditor=ConverterEditorUtils.getBasicConverter(vCls);
					valEditor.setValue(val.get(k));
					vval=valEditor.getSource();
				}
				json.put(keyEditor.getSource().toString(),vval);
			}
			setSource(json);
		}
	}

}
